package javaCode;

import java.util.*;

/**
 * Created by lxy_920912 on 14/04/2017.
 */
public class LeetCode227 {
    public int calculate(String s) {
        int result = 0;

        Stack<Integer> numStack = new Stack<>();
        Stack<Character> optStack = new Stack<>();

        int k = 0;
        int num = 0;
        for(int i = 0;i < s.length();i++){
            if(s.charAt(i) == ' '){
                continue;
            }
            if(s.charAt(i)>='0' && s.charAt(i) <='9'){
                num = (num*10)+(s.charAt(i)-'0');
            }else{
                if(optStack.isEmpty()){
                    numStack.push(num);
                    optStack.push(s.charAt(i));
                    num = 0;
                    continue;
                }
                char x = optStack.peek();
                if(x == '/'){
                    int num1 = numStack.pop();
                    numStack.push(num1/num);
                    optStack.pop();
                }else if( x == '*'){
                    int num1 = numStack.pop();
                    numStack.push(num1*num);
                    optStack.pop();
                }else{
                    numStack.push(num);
                }
                optStack.push(s.charAt(i));
                num = 0;
            }
        }
        numStack.push(num);
        if(!optStack.isEmpty()){
            char x = optStack.peek();
            if(x == '*'){
                int num2 = numStack.pop();
                int num1 = numStack.pop();
                numStack.push(num1*num) ;
                optStack.pop();
            }
            if(x == '/'){
                int num2 = numStack.pop();
                int num1 = numStack.pop();
                numStack.push(num1/num);
                optStack.pop();
            }

            Stack<Integer> num2Stack = new Stack<>();
            Stack<Character> opt2Stack = new Stack<>();
            while(!numStack.isEmpty()){
                num2Stack.push(numStack.pop());
            }
            while(!optStack.isEmpty()){
                opt2Stack.push(optStack.pop());
            }
            optStack = opt2Stack;
            numStack = num2Stack;
            while(!optStack.isEmpty()){
                int num1 = numStack.pop();
                int num2 = numStack.pop();
                x = optStack.pop();
                if(x == '+'){
                    numStack.push(num2+num1);
                }else{
                    numStack.push(num1-num2);
                }
            }
        }

        return numStack.pop();
    }
}
